package development.game;

import java.util.Vector;

import state.GameAlert;
import state.GameConstants;
import state.GameForm;
import state.GameGlobal;
import state.GameImage;
import state.Graphics;
import state.Key;
import state.TimerListener;
import state.font.FontManager;
import state.font.ImageFont;
import state.font.ImageText;
import state.socket.DataPackage;
import state.socket.DataReceiveListener;
import state.util.GameColor;
import state.util.GameStringUtils;
import state.util.ImageUtil;
import state.util.array.StringArray;
import development.Constants;
import development.DrawUtils;
import development.Global;
import development.bean.Game;
import development.bean.Question;
import development.group.FrmGroupListTableFreeUserChat;
import development.group.FrmGroupTableFreeUserFriend;
import development.socket.SocketClientUtil;

public class FrmAiLaTrieuPhu extends GameForm implements DataReceiveListener, TimerListener {
  private ImageText text;
  private final int SEND_QUESTION = 3002;
  private final int SELECT_TO_ANSWER = 3003;
  private final int SEND_RESULT_AFTER_ANSWER = 3004;
  private final int FINISHED_QUESTION = 3006;
  private final int FINISH_GAME = 3008;
  private final int ADD_BONUS = 3009;
  private final int LEAVE_TABLE_REQUEST = 3010;
  private final int WIN_BECAUSE_ALONE = 3011;
  private static final int INIT_FOR_VIEW_USER_HEADER = 4023;
  private static final int USER_VIEW_JOIN_HEADER = 4024;
  private static final int SEND_READY_REQUEST_HEADER = 4025;
  private static final int DS_USERS_HEARDER = 4010;
  private static GameForm singleton;
  private int STATE_SCREEN;
  public Vector tableUsers;
  private int numberOfPlayer;
  Question question;
  int timePerQuestion;
  int count;
  private String dapAnDung;
  int[] obtainScores;
  private String[] userResult;
  private int currentQuestionIndex;
  private int selectedIndexAnswer;
  private boolean isAnswered;
  private GameImage backgroundImg;
  private GameImage questionsBoxImg;
  private GameImage menulevel;
  private GameImage iconTrieuphuImg;
  private GameImage linetop2Img;
  private GameImage questionBoxImg;
  private GameImage answerBoxImg;
  private GameImage anseredBoxImg;
  private GameImage userGround1;
  private int[] bonus;
  private boolean isEndGame;
  private boolean isShowResultPerQuestion;
  private int[] scorePerQuestion;
  private boolean isErrorData;
  private GameImage confirmAnswerImg;
  private GameImage buttonImg;
  private GameImage buttonImg1;
  private int myScoure;
  private boolean[] isUsersLeft;
  private String[] users;
  private boolean isConfirmSeclectAnswer;
  private String[] results;
  private boolean isOk;
  private int[] bids;
  private boolean isWinCauseAlone;
  private int leaveIndex;
  private boolean isViewUser;
  private int soNguoiChoi;
  private boolean[] isViewerUser;
  private GameImage[] avatarImgs;

  public static GameForm instance() {
    if (singleton == null) {
      singleton = new FrmAiLaTrieuPhu();
    }
    return singleton;
  }

  public void init(java.util.Hashtable parameters) {
    isConfirmSeclectAnswer = false;
    isAnswered = false;
    selectedIndexAnswer = 0;
    tableUsers = Global.tableUsers;
    timePerQuestion = 0;
    isOk = true;
    leaveIndex = 0;
    numberOfPlayer = 4;
    results = new String[] { "A", "B", "C", "D" };
    isShowResultPerQuestion = false;
    isEndGame = false;
    text = FontManager.getFont(FontManager.FONT_SIZE_8);
    STATE_SCREEN = 0;
    isErrorData = false;
    myScoure = 0;
    dapAnDung = "";
    if (Constants.IS_240x320_SCREEN) {
      backgroundImg = ImageUtil.getImage(Constants.AI_LA_TRIEU_PHU_IMAGE_CATEGORY, "background.png");
      linetop2Img = ImageUtil.getImage(Constants.AI_LA_TRIEU_PHU_IMAGE_CATEGORY, "line-top2.png");
    } else {
      backgroundImg = ImageUtil.getImage(Constants.AI_LA_TRIEU_PHU_IMAGE_CATEGORY, "background_320.png");
      linetop2Img = ImageUtil.getImage(Constants.AI_LA_TRIEU_PHU_IMAGE_CATEGORY, "line-top_320.png");
    }
    buttonImg = ImageUtil.getImage(Constants.AI_LA_TRIEU_PHU_IMAGE_CATEGORY, "button1.png");
    buttonImg1 = ImageUtil.getImage(Constants.AI_LA_TRIEU_PHU_IMAGE_CATEGORY, "button2.png");
    confirmAnswerImg = ImageUtil.getImage(Constants.AI_LA_TRIEU_PHU_IMAGE_CATEGORY, "box-xac-nhan-lai.png");
    questionsBoxImg = ImageUtil.getImage(Constants.AI_LA_TRIEU_PHU_IMAGE_CATEGORY, "box-cau-hoi-so-tien.png");
    menulevel = ImageUtil.getImage(Constants.AI_LA_TRIEU_PHU_IMAGE_CATEGORY, "cau-hoi-da-tra-loi.png");
    iconTrieuphuImg = ImageUtil.getImage(Constants.AI_LA_TRIEU_PHU_IMAGE_CATEGORY, "2-trieu-phu.png");
    questionBoxImg = ImageUtil.getImage(Constants.AI_LA_TRIEU_PHU_IMAGE_CATEGORY, "box-cau-hoi.png");
    answerBoxImg = ImageUtil.getImage(Constants.AI_LA_TRIEU_PHU_IMAGE_CATEGORY, "box-tra-loi.png");
    anseredBoxImg = ImageUtil.getImage(Constants.AI_LA_TRIEU_PHU_IMAGE_CATEGORY, "box-tra-loi-lua-chon.png");
    userGround1 = ImageUtil.getImage(Constants.AI_LA_TRIEU_PHU_IMAGE_CATEGORY, "nen1.png");

    setTimerListener(this);
    GameGlobal.systemCanvas.setTimerDelay(100);
    DrawUtils.setBottomBar(_manager, "", "", "Thoát");
    DataPackage dataPackage = Game.createGamePackage(SEND_READY_REQUEST_HEADER);
    Global.gameActionClient.write(dataPackage);
    _manager.enableTouchPad();
  }

  public void initInfos() {
    currentQuestionIndex = 0;
    tableUsers = Global.tableUsers;
    numberOfPlayer = 4;
    obtainScores = new int[numberOfPlayer];
    bonus = new int[numberOfPlayer];
    scorePerQuestion = new int[numberOfPlayer];
    userResult = new String[numberOfPlayer];
    isUsersLeft = new boolean[4];
    users = new String[] { "", "", "", "" };
    isViewerUser = new boolean[4];
    soNguoiChoi = tableUsers.size();
    avatarImgs = new GameImage[4];
    bids = new int[4];
    for (int i = 0; i < numberOfPlayer; i++) {
      isUsersLeft[i] = false;
      isViewerUser[i] = false;
      bids[i] = 0;
    }
  }

  public void draw(Graphics g) {
    g.drawImage(backgroundImg, 0, 0, GameConstants.TOP_LEFT_ANCHOR);
    if (Constants.IS_240x320_SCREEN) {
      if (STATE_SCREEN == 2) {
        drawQuestion_240(g);
        if (!isAnswered) {
          if (!isViewUser) {
            DrawUtils.setBottomBar(_manager, "", "Chọn", "Thoát");
          }
        } else {
          DrawUtils.setBottomBar(_manager, "", "", "Thoát");
        }
        if (isEndGame) {
          DrawUtils.drawHozPopup(g, Constants.SCREEN_WIDTH - 10, 5, 82);
          text.drawString2(g, "KẾT QUẢ", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH / 2, 90, GameConstants.TOP_HCENTER_ANCHOR);
          g.setColor(GameColor.RED2_CODE);
          g.drawLine(28, 105, 205, 105);
          if (!isWinCauseAlone) {
            for (int i = 0; i < soNguoiChoi; i++) {
              if (!isViewerUser[i]) {
                if (i == 0) {
                  if (obtainScores[0] == 0) {
                    text.drawString2(g, "Hòa: ", GameColor.WHITE_CODE, 15, 110 + i * 15, GameConstants.TOP_LEFT_ANCHOR);
                  } else {
                    text.drawString2(g, "Thắng: ", GameColor.WHITE_CODE, 15, 110 + i * 15, GameConstants.TOP_LEFT_ANCHOR);
                  }
                } else {
                  if (obtainScores[0] == 0) {
                    text.drawString2(g, "Hòa: ", GameColor.WHITE_CODE, 15, 110 + i * 15, GameConstants.TOP_LEFT_ANCHOR);
                  } else {
                    text.drawString2(g, "Thua: ", GameColor.WHITE_CODE, 15, 110 + i * 15, GameConstants.TOP_LEFT_ANCHOR);
                  }
                }
                text.drawString2(g, userResult[i] + ": " + obtainScores[i] + " điểm" + "  " + bids[i] + " gold", GameColor.WHITE_CODE, 60, 110 + i * 15, GameConstants.TOP_LEFT_ANCHOR);
              }
            }
          } else {
            text.drawString2(g, "Thắng: ", GameColor.WHITE_CODE, 15, 110, GameConstants.TOP_LEFT_ANCHOR);
            text.drawString2(g, Global.currentUser.getName() + ": " + obtainScores[0] + " điểm" + "  +" + bids[0] + " gold", GameColor.WHITE_CODE, 60, 110, GameConstants.TOP_LEFT_ANCHOR);
            for (int i = 1; i < soNguoiChoi; i++) {
              text.drawString2(g, "Thua: ", GameColor.WHITE_CODE, 15, 110 + i * 15, GameConstants.TOP_LEFT_ANCHOR);
              text.drawString2(g, userResult[i] + ": " + 0 + " điểm" + "  -" + bids[i] + " gold", GameColor.WHITE_CODE, 60, 110 + i * 15, GameConstants.TOP_LEFT_ANCHOR);
            }
          }
          DrawUtils.setBottomBar(_manager, "", "Chơi tiếp", "Trở về");
        }
      } else {
        drawLevel(g);
      }
    } else {
      if (STATE_SCREEN == 2) {
        drawQuestion320(g);
        if (!isAnswered) {
          if (!isViewUser) {
            DrawUtils.setBottomBar(_manager, "", "Chọn", "Thoát");
          }
        } else {
          DrawUtils.setBottomBar(_manager, "", "", "Thoát");
        }
        if (isEndGame) {
          DrawUtils.drawHozPopup(g, 230, 45, 82);
          text.drawString2(g, "KẾT QUẢ", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH / 2, 84, GameConstants.TOP_HCENTER_ANCHOR);
          g.setColor(GameColor.RED2_CODE);
          g.drawLine(66, 101, 240, 101);
          if (!isWinCauseAlone) {
            for (int i = 0; i < soNguoiChoi; i++) {
              if (!isViewerUser[i]) {
                if (i == 0) {
                  if (obtainScores[0] == 0) {
                    text.drawString2(g, "Hòa: ", GameColor.WHITE_CODE, 50, 110 + i * 15, GameConstants.TOP_LEFT_ANCHOR);
                  } else {
                    text.drawString2(g, "Thắng: ", GameColor.WHITE_CODE, 50, 110 + i * 15, GameConstants.TOP_LEFT_ANCHOR);
                  }
                } else {
                  if (obtainScores[0] == 0) {
                    text.drawString2(g, "Hòa: ", GameColor.WHITE_CODE, 50, 110 + i * 15, GameConstants.TOP_LEFT_ANCHOR);
                  } else {
                    text.drawString2(g, "Thua: ", GameColor.WHITE_CODE, 50, 110 + i * 15, GameConstants.TOP_LEFT_ANCHOR);
                  }
                }
                text.drawString2(g, userResult[i] + ": " + obtainScores[i] + "điểm" + "  " + bids[i] + " gold", GameColor.WHITE_CODE, 95, 110 + i * 15, GameConstants.TOP_LEFT_ANCHOR);
              }
            }
          } else {
            text.drawString2(g, "Thắng: ", GameColor.WHITE_CODE, 50, 110, GameConstants.TOP_LEFT_ANCHOR);
            text.drawString2(g, Global.currentUser.getName() + ": " + obtainScores[0] + " điểm" + "  +" + bids[0] + " gold", GameColor.WHITE_CODE, 95, 110, GameConstants.TOP_LEFT_ANCHOR);
            for (int i = 1; i < soNguoiChoi; i++) {
              text.drawString2(g, "Thua: ", GameColor.WHITE_CODE, 50, 110 + i * 15, GameConstants.TOP_LEFT_ANCHOR);
              text.drawString2(g, userResult[i] + ": " + 0 + " điểm" + "  -" + bids[i] + " gold", GameColor.WHITE_CODE, 95, 110 + i * 15, GameConstants.TOP_LEFT_ANCHOR);
            }
          }
          DrawUtils.setBottomBar(_manager, "", "Chơi tiếp", "Thoát");
        }
      } else {
        drawLevel(g);
      }
    }
  }

  public void drawQuestion_240(Graphics g) {
    if (!isErrorData && !isEndGame) {
      g.drawImage(iconTrieuphuImg, Constants.SCREEN_WIDTH / 2, 45, GameConstants.CENTER_ANCHOR);
      g.drawImage(linetop2Img, GameConstants.SCREEN_WIDTH / 2, 45, GameConstants.CENTER_ANCHOR);
      if (question != null) {
        g.drawImage(questionBoxImg, Constants.SCREEN_WIDTH / 2, 110, GameConstants.CENTER_ANCHOR);
        if (isShowResultPerQuestion) {
          text.drawString2(g, "Đáp án đúng là: " + dapAnDung, GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH / 2, 110, GameConstants.CENTER_ANCHOR);
        } else {
          text.drawParagraph1(g, question.getContent(), GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH - 40, -5, 17, 85);
        }
        g.drawImage(answerBoxImg, 6, 155, GameConstants.VCENTER_LEFT_ANCHOR);
        g.drawImage(answerBoxImg, 6, 187, GameConstants.VCENTER_LEFT_ANCHOR);
        g.drawImage(answerBoxImg, GameConstants.SCREEN_WIDTH / 2 + 10, 155, GameConstants.VCENTER_LEFT_ANCHOR);
        g.drawImage(answerBoxImg, GameConstants.SCREEN_WIDTH / 2 + 10, 187, GameConstants.VCENTER_LEFT_ANCHOR);

        if (selectedIndexAnswer == 0) {
          g.drawImage(anseredBoxImg, 6, 155, GameConstants.VCENTER_LEFT_ANCHOR);
          text.drawParagraph1(g, question.getResult1(), GameColor.YELLOW_CODE, 98, -5, 12, 142);
          text.drawParagraph1(g, question.getResult2(), GameColor.WHITE_CODE, 98, -5, 135, 142);
          text.drawParagraph1(g, question.getResult3(), GameColor.WHITE_CODE, 98, -5, 12, 172);
          text.drawParagraph1(g, question.getResult4(), GameColor.WHITE_CODE, 98, -5, 135, 172);
        } else if (selectedIndexAnswer == 1) {
          g.drawImage(anseredBoxImg, GameConstants.SCREEN_WIDTH / 2 + 10, 155, GameConstants.VCENTER_LEFT_ANCHOR);
          text.drawParagraph1(g, question.getResult1(), GameColor.WHITE_CODE, 98, -5, 12, 142);
          text.drawParagraph1(g, question.getResult2(), GameColor.YELLOW_CODE, 98, -5, 135, 142);
          text.drawParagraph1(g, question.getResult3(), GameColor.WHITE_CODE, 98, -5, 12, 172);
          text.drawParagraph1(g, question.getResult4(), GameColor.WHITE_CODE, 98, -5, 135, 172);
        } else if (selectedIndexAnswer == 2) {
          g.drawImage(anseredBoxImg, 6, 187, GameConstants.VCENTER_LEFT_ANCHOR);
          text.drawParagraph1(g, question.getResult1(), GameColor.WHITE_CODE, 98, -5, 12, 142);
          text.drawParagraph1(g, question.getResult2(), GameColor.WHITE_CODE, 98, -5, 135, 142);
          text.drawParagraph1(g, question.getResult3(), GameColor.YELLOW_CODE, 98, -5, 12, 172);
          text.drawParagraph1(g, question.getResult4(), GameColor.WHITE_CODE, 98, -5, 135, 172);

        } else if (selectedIndexAnswer == 3) {
          g.drawImage(anseredBoxImg, GameConstants.SCREEN_WIDTH / 2 + 10, 187, GameConstants.VCENTER_LEFT_ANCHOR);
          text.drawParagraph1(g, question.getResult1(), GameColor.WHITE_CODE, 98, -5, 12, 142);
          text.drawParagraph1(g, question.getResult2(), GameColor.WHITE_CODE, 98, -5, 135, 142);
          text.drawParagraph1(g, question.getResult3(), GameColor.WHITE_CODE, 98, -5, 12, 172);
          text.drawParagraph1(g, question.getResult4(), GameColor.YELLOW_CODE, 98, -5, 135, 172);
        }
      }
      if (!"".equals(users[0])) {
        if (!isUsersLeft[0]) {
          drawUserInfo(g, userGround1, users[0], 12, 208, false);
        }
      }
      if (!"".equals(users[1])) {
        if (!isUsersLeft[1]) {
          drawUserInfo(g, userGround1, users[1], 135, 208, false);
        }
      }
      if (!"".equals(users[2])) {
        if (!isUsersLeft[2]) {
          drawUserInfo(g, userGround1, users[2], 12, 255, true);
        }
      }
      if (!"".equals(users[3])) {
        if (!isUsersLeft[3]) {
          drawUserInfo(g, userGround1, users[3], 135, 255, true);
        }
      }

      text.drawString2(g, String.valueOf(myScoure), GameColor.BLUE_CODE, 25, 45, GameConstants.VCENTER_LEFT_ANCHOR);
      text.drawString2(g, "00:" + timePerQuestion, GameColor.BLUE_CODE, GameConstants.SCREEN_WIDTH - 55, 45, GameConstants.VCENTER_LEFT_ANCHOR);
      if (isConfirmSeclectAnswer) {
        drawConfirm(g, results[selectedIndexAnswer] + " Là đáp án cuối cùng của bạn?", true);
      }
    } else {
      if (!isEndGame) {
        drawConfirm(g, "Lỗi dữ liệu! Mời bạn trở về sau");
      }
    }
  }

  public void drawConfirm(Graphics g, String s, boolean isHasButton) {
    g.drawImage(confirmAnswerImg, GameConstants.SCREEN_WIDTH / 2, 146, GameConstants.CENTER_ANCHOR);
    text.drawString2(g, s + "", GameColor.YELLOW_CODE, GameConstants.SCREEN_WIDTH / 2, 127, GameConstants.CENTER_ANCHOR);
    if (isHasButton) {
      if (isOk) {
        g.drawImage(buttonImg1, GameConstants.SCREEN_WIDTH / 2 - 20, 153, GameConstants.VCENTER_RIGHT_ANCHOR);
        g.drawImage(buttonImg, GameConstants.SCREEN_WIDTH / 2 + 20, 153, GameConstants.VCENTER_LEFT_ANCHOR);
      } else {
        g.drawImage(buttonImg, GameConstants.SCREEN_WIDTH / 2 - 20, 153, GameConstants.VCENTER_RIGHT_ANCHOR);
        g.drawImage(buttonImg1, GameConstants.SCREEN_WIDTH / 2 + 20, 153, GameConstants.VCENTER_LEFT_ANCHOR);
      }
      text.drawString2(g, "Đồng ý", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH / 2 - 35, 153, GameConstants.VCENTER_RIGHT_ANCHOR);
      text.drawString2(g, "Hủy", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH / 2 + 40, 153, GameConstants.VCENTER_LEFT_ANCHOR);
    }
  }

  public void drawConfirm(Graphics g, String s) {
    g.drawImage(confirmAnswerImg, GameConstants.SCREEN_WIDTH / 2, 146, GameConstants.CENTER_ANCHOR);
    text.drawString2(g, s + "", GameColor.YELLOW_CODE, GameConstants.SCREEN_WIDTH / 2, 127, GameConstants.CENTER_ANCHOR);
    g.drawImage(buttonImg, GameConstants.SCREEN_WIDTH / 2, 153, GameConstants.CENTER_ANCHOR);
    text.drawString2(g, "Đồng ý", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH / 2, 153, GameConstants.CENTER_ANCHOR);
  }

  public void drawQuestion320(Graphics g) {
    if (!isErrorData && !isEndGame) {
      g.drawImage(iconTrieuphuImg, Constants.SCREEN_WIDTH / 2, 41, GameConstants.CENTER_ANCHOR);
      g.drawImage(linetop2Img, GameConstants.SCREEN_WIDTH / 2, 41, GameConstants.CENTER_ANCHOR);
      if (question != null) {
        g.drawImage(questionBoxImg, 93, 75, GameConstants.TOP_LEFT_ANCHOR);
        if (isShowResultPerQuestion) {
          text.drawString2(g, "Đáp án đúng là: " + dapAnDung, GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH / 2 + 30, 75 + questionBoxImg.getHeight() / 2, GameConstants.CENTER_ANCHOR);
        } else {
          text.drawParagraph1(g, question.getContent(), GameColor.WHITE_CODE, 200, -5, 97, 75);
        }
        g.drawImage(answerBoxImg, 97, 140, GameConstants.TOP_LEFT_ANCHOR);
        g.drawImage(answerBoxImg, 97, 180, GameConstants.TOP_LEFT_ANCHOR);
        g.drawImage(answerBoxImg, 210, 140, GameConstants.TOP_LEFT_ANCHOR);
        g.drawImage(answerBoxImg, 210, 180, GameConstants.TOP_LEFT_ANCHOR);

        if (selectedIndexAnswer == 0) {
          g.drawImage(anseredBoxImg, 96, 139, GameConstants.TOP_LEFT_ANCHOR);
          text.drawParagraph1(g, question.getResult1(), GameColor.YELLOW_CODE, 98, -5, 100, 140);
          text.drawParagraph1(g, question.getResult2(), GameColor.WHITE_CODE, 98, -5, 220, 140);
          text.drawParagraph1(g, question.getResult3(), GameColor.WHITE_CODE, 98, -5, 100, 180);
          text.drawParagraph1(g, question.getResult4(), GameColor.WHITE_CODE, 98, -5, 220, 180);
        } else if (selectedIndexAnswer == 1) {
          g.drawImage(anseredBoxImg, 209, 139, GameConstants.TOP_LEFT_ANCHOR);
          text.drawParagraph1(g, question.getResult1(), GameColor.WHITE_CODE, 98, -5, 100, 140);
          text.drawParagraph1(g, question.getResult2(), GameColor.YELLOW_CODE, 98, -5, 220, 140);
          text.drawParagraph1(g, question.getResult3(), GameColor.WHITE_CODE, 98, -5, 100, 180);
          text.drawParagraph1(g, question.getResult4(), GameColor.WHITE_CODE, 98, -5, 220, 180);
        } else if (selectedIndexAnswer == 2) {
          g.drawImage(anseredBoxImg, 96, 179, GameConstants.TOP_LEFT_ANCHOR);
          text.drawParagraph1(g, question.getResult1(), GameColor.WHITE_CODE, 98, -5, 100, 140);
          text.drawParagraph1(g, question.getResult2(), GameColor.WHITE_CODE, 98, -5, 220, 140);
          text.drawParagraph1(g, question.getResult3(), GameColor.YELLOW_CODE, 98, -5, 100, 180);
          text.drawParagraph1(g, question.getResult4(), GameColor.WHITE_CODE, 98, -5, 220, 180);
        } else if (selectedIndexAnswer == 3) {
          g.drawImage(anseredBoxImg, 209, 179, GameConstants.TOP_LEFT_ANCHOR);
          text.drawParagraph1(g, question.getResult1(), GameColor.WHITE_CODE, 98, -5, 100, 140);
          text.drawParagraph1(g, question.getResult2(), GameColor.WHITE_CODE, 98, -5, 220, 140);
          text.drawParagraph1(g, question.getResult3(), GameColor.WHITE_CODE, 98, -5, 100, 180);
          text.drawParagraph1(g, question.getResult4(), GameColor.YELLOW_CODE, 98, -5, 220, 180);
        }

      }
      if (!"".equals(users[0])) {
        if (!isUsersLeft[0]) {
          drawUserInfo(g, userGround1, users[0], 0, 73, false);
        }
      }
      if (!"".equals(users[1])) {
        if (!isUsersLeft[1]) {
          drawUserInfo(g, userGround1, users[1], 0, 73 + 1 * 40, false);
        }
      }
      if (!"".equals(users[2])) {
        if (!isUsersLeft[2]) {
          drawUserInfo(g, userGround1, users[2], 0, 73 + 2 * 40, false);
        }
      }
      if (!"".equals(users[3])) {
        if (!isUsersLeft[3]) {
          drawUserInfo(g, userGround1, users[3], 0, 73 + 3 * 40, false);
        }
      }
      text.drawString2(g, String.valueOf(myScoure), GameColor.BLUE_CODE, 50, 41, GameConstants.VCENTER_LEFT_ANCHOR);
      text.drawString2(g, "00:" + timePerQuestion, GameColor.BLUE_CODE, 230, 41, GameConstants.VCENTER_LEFT_ANCHOR);
      if (isConfirmSeclectAnswer) {
        drawConfirm(g, results[selectedIndexAnswer] + " Là đáp án cuối cùng của bạn?", true);
      }
    } else {
      if (!isEndGame) {
        drawConfirm(g, "Lỗi dữ liệu! Mời bạn trở về sau");
      }
    }
  }

  public void drawUserInfo(Graphics g, GameImage imgGround, String username, int x, int y, boolean isMirror) {
    g.drawImage(imgGround, x, y, GameConstants.TOP_LEFT_ANCHOR);
    ImageFont text8 = FontManager.getFont(FontManager.FONT_SIZE_8);
    if (!isMirror) {
      text8.drawString2(g, username, 0x2E5799, x + 30, y + 18, GameConstants.TOP_LEFT_ANCHOR);
      if (!isViewerUser[getUserIndex(username)]) {
        text8.drawString2(g, "$" + obtainScores[getUserIndex(username)], 0x99730E, x + 30, y, GameConstants.TOP_LEFT_ANCHOR);
      }
      g.drawImage(avatarImgs[getUserIndex(username)], x + 2, y + imgGround.getHeight() / 2, GameConstants.VCENTER_LEFT_ANCHOR);
    } else {
      text8.drawString2(g, username, 0x2E5799, x + 10, y + 18, GameConstants.TOP_LEFT_ANCHOR);
      if (!isViewerUser[getUserIndex(username)]) {
        text8.drawString2(g, "$" + obtainScores[getUserIndex(username)], 0x99730E, x + 10, y, GameConstants.TOP_LEFT_ANCHOR);
      }
      g.drawImage(avatarImgs[getUserIndex(username)], x + imgGround.getWidth() - 2, y + imgGround.getHeight() / 2, GameConstants.VCENTER_RIGHT_ANCHOR);
    }
    g.setColor(GameColor.YELLOW_CODE);
    if (isShowResultPerQuestion) {
      if (!isViewerUser[getUserIndex(username)]) {
        text.drawString2(g, "+" + String.valueOf(bonus[getUserIndex(username)]), GameColor.RED_CODE, x + imgGround.getWidth(), y + 5, Constants.TOP_RIGHT_ANCHOR);
      }
    }
  }

  public void drawLevel(Graphics g) {
    int dy;
    if (Constants.IS_240x320_SCREEN) {
      dy = 50;
    } else {
      dy = 30;
    }
    g.drawImage(questionsBoxImg, Constants.SCREEN_WIDTH - 10, dy, Constants.TOP_RIGHT_ANCHOR);
    g.drawImage(menulevel, Constants.SCREEN_WIDTH - 10, dy - 17 + questionsBoxImg.getHeight() - (currentQuestionIndex * 11), Constants.TOP_RIGHT_ANCHOR);
    if (!"".equals(users[0])) {
      if (!isUsersLeft[0]) {
        drawUserInfo(g, userGround1, users[0], 5, 30 + 0 * 40, false);
      }
    }
    if (!"".equals(users[1])) {
      if (!isUsersLeft[1]) {
        drawUserInfo(g, userGround1, users[1], 5, 30 + 1 * 40, false);
      }
    }
    if (!"".equals(users[2])) {
      if (!isUsersLeft[2]) {
        drawUserInfo(g, userGround1, users[2], 5, 30 + 2 * 40, false);
      }
    }
    if (!"".equals(users[3])) {
      if (!isUsersLeft[3]) {
        drawUserInfo(g, userGround1, users[3], 5, 30 + 3 * 40, false);
      }
    }
    /*
     * } else { g.drawImage(questionsBoxImg, Constants.SCREEN_WIDTH - 10, 17, Constants.TOP_RIGHT_ANCHOR); g.drawImage(menulevel, Constants.SCREEN_WIDTH - 10, questionsBoxImg.getHeight() -
     * (currentQuestionIndex * 11), Constants.TOP_RIGHT_ANCHOR); for (int i = 0; i < numberOfPlayer; i ++) { drawUserInfo(g, userGround1, users[i], 5, 30 + i *40, false); } }
     */
  }

  public void alertEventPerform(int alertType, int eventType, int alertId) {
    if (alertId == 99 && eventType == GameAlert.YES_BUTTON) {
      SocketClientUtil.leaveTableRequest();
      GameGlobal.nextState(FrmGroupListTableFreeUserChat.instance(), null);
    }
  }

  public void keyReleased(int keyCode) {
    switch (keyCode) {
    case Key.RIGHT:
      if (!isViewUser) {
        if (isConfirmSeclectAnswer) {
          isOk = !isOk;
        } else if (STATE_SCREEN == 2) {
          selectedIndexAnswer = (selectedIndexAnswer + 1) % 4;
        }
      }
      break;
    case Key.LEFT:
      if (!isViewUser) {
        if (isConfirmSeclectAnswer) {
          isOk = !isOk;
        } else {
          if (STATE_SCREEN == 2) {
            selectedIndexAnswer -= 1;
            if (selectedIndexAnswer < 0) {
              selectedIndexAnswer = 3;
            }
          }
        }
      }
      break;
    case Key.DOWN:
      if (!isViewUser) {
        if (STATE_SCREEN == 2) {
          selectedIndexAnswer = (selectedIndexAnswer + 1) % 4;
        }
      }
      break;
    case Key.UP:
      if (!isViewUser) {
        if (STATE_SCREEN == 2) {
          selectedIndexAnswer -= 1;
          if (selectedIndexAnswer < 0) {
            selectedIndexAnswer = 3;
          }
        }
      }
      break;
    case Key.FIRE:
      if (!isEndGame) {
        if (!isViewUser) {
          if (selectedIndexAnswer >= 0 && !isAnswered) {
            if (isConfirmSeclectAnswer) {
              if (isOk) {
                isConfirmSeclectAnswer = false;
                isAnswered = true;
                sendMessageAction(SELECT_TO_ANSWER, selectedIndexAnswer, timePerQuestion);
              } else {
                isConfirmSeclectAnswer = false;
              }
            } else {
              isConfirmSeclectAnswer = true;
            }
          }
        }
      } else {
        isViewUser = false;
        GameGlobal.nextState(FrmGroupTableFreeUserFriend.instance(), null);
      }
      break;
    case Key.SOFT_RIGHT:
      if (isViewUser) {
        SocketClientUtil.leaveTableRequest();
        GameGlobal.nextState(FrmGroupListTableFreeUserChat.instance(), null);
      } else {
        if (!isEndGame) {
          if (numberOfPlayer > 1) {
            Global.alert.showAlert1(this, GameAlert.YES_NO_TYPE, StringArray.create1( "Thoát ra ra sẽ bị phạt tiền", "Bạn có muốn thoát" ), 99);
          } else {
            SocketClientUtil.leaveTableRequest();
            GameGlobal.nextState(FrmGroupListTableFreeUserChat.instance(), null);
            return;
          }
        } else {
          SocketClientUtil.leaveTableRequest();
          GameGlobal.nextState(FrmGroupListTableFreeUserChat.instance(), null);
          return;
        }
      }
      break;
    default:
      break;
    }
  }

  public void onConnectDone() {
  }

  public void onConnectFail() {
  }

  public void onDisconnect() {
  }

  public void onRecieveData(DataPackage dataPackage) {
    int header = dataPackage.getHeader();
    switch (header) {
    case DS_USERS_HEARDER:
      dataPackage.nextString();
      String usersStr = dataPackage.nextString();
      StringArray strr = GameStringUtils.split(usersStr, ":");
      int length = strr.len();
      initInfos();
      for (int i = 0; i < length; i++) {
        users[i] = strr.array[i];
        avatarImgs[i] = ImageUtil.resizeImage1(Global.getAvatar(users[i]), 0.5f, 0, 0, true);
      }
      break;
    case SEND_QUESTION:
      isAnswered = false;
      isOk = true;
      STATE_SCREEN = 2;
      question = new Question();
      String s = dataPackage.nextString();
      if (s.equals("NULL")) {
        isErrorData = true;
      } else {
        String[] data = split1(s, "@@@");
        question.setContent(data[0]);
        question.setResult1(data[1]);
        question.setResult2(data[2]);
        question.setResult3(data[3]);
        question.setResult4(data[4]);
        if ("null".equals(question.getContent().trim()) || question.getContent() == null) {
          isErrorData = true;
        }
        for (int i = 0; i < numberOfPlayer; i++) {
          bonus[i] = 0;
          // scorePerQuestion[i] = 0;
        }
        timePerQuestion = 0;
      }
      break;
    case SEND_RESULT_AFTER_ANSWER:
      String user = dataPackage.nextString();
      int sc = dataPackage.nextInt();
      int bn = dataPackage.nextInt();
      int index = getUserIndex(user);
      bonus[index] = bn;
      scorePerQuestion[index] = sc;
      STATE_SCREEN = 2;
      break;
    case FINISHED_QUESTION:
      currentQuestionIndex = dataPackage.nextInt();
      dapAnDung = dataPackage.nextString();
      for (int i = 0; i < numberOfPlayer; i++) {
        if (!isViewerUser[i]) {
          obtainScores[i] = scorePerQuestion[i];
          if (Global.currentUser.getName().equals(users[i])) {
            myScoure = obtainScores[i];
          }
        } else if (isViewUser) {
          myScoure = 0;
          obtainScores[getUserIndex(Global.currentUser.getName())] = 0;
        } else {
          obtainScores[i] = 0;
        }
      }
      isShowResultPerQuestion = true;
      break;
    case ADD_BONUS:
      for (int i = 0; i < numberOfPlayer; i++) {
        scorePerQuestion[i] += bonus[i];
        obtainScores[i] = scorePerQuestion[i];
        if (Global.currentUser.getName().equals(users[i])) {
          myScoure = obtainScores[i];
        }
      }
      STATE_SCREEN = 1;
      isShowResultPerQuestion = false;
      break;
    case FINISH_GAME:
      String str = dataPackage.nextString();
      int size = dataPackage.nextInt();
      userResult = split1(str, "@@@");
      for (int i = 0; i < size; i++) {
        obtainScores[i] = dataPackage.nextInt();
      }
      for (int i = 0; i < size; i++) {
        bids[i] = dataPackage.nextInt();
      }
      isEndGame = true;
//      DrawUtils.setBottomBar(manager, "", "Chơi tiếp", "Thoát");
      break;
    case LEAVE_TABLE_REQUEST:
      String userleft = dataPackage.nextString();
      int isUser = dataPackage.nextInt();
      int indexLeft = getUserIndex(userleft);
      if (isUser == 1) {
        isUsersLeft[indexLeft] = true;
      } else {
        users[indexLeft] = "";
        soNguoiChoi--;
      }

      break;
    case WIN_BECAUSE_ALONE:
      isEndGame = true;
      isWinCauseAlone = true;
      obtainScores[0] = dataPackage.nextInt();
      bids[0] = dataPackage.nextInt();
      int x = dataPackage.nextInt();
      for (int i = 1; i < numberOfPlayer; i++) {
        bids[i] = x;
      }
      Global.alert.showAlert1(this, GameAlert.OK_TYPE, StringArray.create1( "Tất cả đối thủ đã thoát", "Bạn đã thắng" ), 98);
      break;
    case INIT_FOR_VIEW_USER_HEADER:
      System.out.println("INIT_FOR_VIEW_USER_HEADER");
      initForViewUser(dataPackage);
      break;
    case USER_VIEW_JOIN_HEADER:
      onUserViewJoin(dataPackage);
      break;
    }
  }

  private void initForViewUser(DataPackage dataPackage) {
    isViewUser = true;
    int size = dataPackage.nextInt();
    for (int i = 0; i < size; i++) {
      users[i] = dataPackage.nextString();
      obtainScores[i] = dataPackage.nextInt();
      avatarImgs[i] = ImageUtil.resizeImage1(Global.getAvatar(users[i]), 0.5f, 0, 0, true);
    }
    int sizeViewUsers = dataPackage.nextInt();
    for (int i = 0; i < sizeViewUsers; i++) {
      users[size + i] = dataPackage.nextString();
      isViewerUser[size + i] = true;
      avatarImgs[size + i] = ImageUtil.resizeImage1(Global.getAvatar(users[i]), 0.5f, 0, 0, true);
    }
    // users[index] = s;
    currentQuestionIndex = dataPackage.nextInt();
    question = new Question();
    String questionStr = dataPackage.nextString();
    if (questionStr.equals("NULL")) {
      isErrorData = true;
    } else {
      STATE_SCREEN = 2;
      String[] data = split1(questionStr, "@@@");
      question.setContent(data[0]);
      question.setResult1(data[1]);
      question.setResult2(data[2]);
      question.setResult3(data[3]);
      question.setResult4(data[4]);
      if ("null".equals(question.getContent().trim()) || question.getContent() == null) {
        isErrorData = true;
      }
      for (int i = 0; i < numberOfPlayer; i++) {
        bonus[i] = 0;
        scorePerQuestion[i] = 0;
      }
      timePerQuestion = dataPackage.nextInt();
    }
  }

  private void onUserViewJoin(DataPackage dataPackage) {
    String userJoin = dataPackage.nextString();
    for (int i = 0; i < 4; i++) {
      if ("".equals(users[i])) {
        users[i] = userJoin;
        isViewerUser[i] = true;
        avatarImgs[i] = ImageUtil.resizeImage1(Global.getAvatar(users[i]), 0.5f, 0, 0, true);
        break;
      }
    }
    soNguoiChoi++;
  }

  private int getUserIndex(String username) {
    int index;
    for (int i = 0; i < numberOfPlayer; i++) {
      if (username.equals(users[i])) {
        index = i;
        return index;
      }
    }
    return 0;
  }

  private void sendMessageAction(int header, int data, int time) {
    DataPackage dataPackage = Game.createGamePackage(header);
    dataPackage.putInt(data);
    Global.gameActionClient.write(dataPackage);
  }

  public void doTask() {
    count = (count + 1) % 2000;
    if (!isErrorData) {
      if (!isEndGame) {
        if (count % 10 == 0) {
          if (timePerQuestion < 27) {
            timePerQuestion++;
          }
        }
      }
    }

  }

  private String[] split1(String original, String separator) {
    String[] nodes = new String[5];
    // Parse nodes into vector
    int index = original.indexOf(separator);
    int dem = 0;
    while (index >= 0) {
      if (dem < 5) {
        nodes[dem] = original.substring(0, index);
        original = original.substring(index + separator.length());
        index = original.indexOf(separator);
        dem++;
      }
    }
    // Get the last node
    if (dem < 5) {
      nodes[dem] = original;
    }
    return nodes;
  }

  public void destroy() {
    text = null;
    tableUsers = null;
    question = null;
    obtainScores = null;
    backgroundImg = null;
    questionsBoxImg = null;
    menulevel = null;
    iconTrieuphuImg = null;
    linetop2Img = null;
    questionBoxImg = null;
    answerBoxImg = null;
    anseredBoxImg = null;
    userGround1 = null;
    bonus = null;
    scorePerQuestion = null;
    confirmAnswerImg = null;
    buttonImg = null;
    dapAnDung = null;
    results = null;
    userResult = null;
    backgroundImg = null;
    questionsBoxImg = null;
    menulevel = null;
    iconTrieuphuImg = null;
    linetop2Img = null;
    questionBoxImg = null;
    answerBoxImg = null;
    anseredBoxImg = null;
    userGround1 = null;
    buttonImg1 = null;
    isUsersLeft = null;
    users = null;
    bids = null;
    isViewerUser = null;
  }

}
